package br.com.pnfp.web.control.actions.cupom;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.dao.EmptyResultDataAccessException;

import br.com.pnfp.web.control.actions.DefaultAction;
import br.com.pnfp.web.control.forms.cupom.CupomForm;
import br.com.pnfp.web.model.vo.Cupom;
import br.com.pnfp.web.model.vo.Doador;
import br.com.pnfp.web.model.vo.Entidade;

public class CupomAction extends DefaultAction {
	
	private static final Logger logger = Logger.getLogger(CupomAction.class);
	
	public ActionForward iniciar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		return mapping.findForward("incluir");
	}
	
	public ActionForward incluir(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CupomForm cupomForm = (CupomForm) form;
		
		Cupom vo = new Cupom();
		vo.setDoador(new Doador(cupomForm.getDoador()));
		vo.setData(getDateFormat().parse(cupomForm.getData()));
		vo.setValor(DecimalFormat.getInstance().parse(cupomForm.getValor()).doubleValue());
		vo.setCoo(cupomForm.getCoo());
		vo.setUsuarioSistema(getUsuario(request));
		
		Cupom verifica = getCupomDAO().validaCupomCadastrado(vo);
		String[] resposta = {"true"};
		if(verifica == null) {
			try {
				Entidade entidade = getDoadorDAO().consultaCliente(vo.getDoador());
				vo.setEntidade(entidade);
			} catch(EmptyResultDataAccessException e) {}

			getCupomDAO().incluir(vo);
		} else {
			String msg = "Nota Fiscal já cadastrada no sistema as: " + getDateHourFormat().format(verifica.getCadastro());
			resposta = new String[]{"false", msg};
		}
		
		printJsonObjectToStream(resposta, response);
		return null;
	}
	
	public ActionForward consultaCupons(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<Cupom> lancamentos = getCupomDAO().consultaCupomLancadosHoje(getUsuario(request));
		
		StringBuilder html = new StringBuilder();
		html.append("<table cellpadding=\"0\" cellspacing=\"1\" style=\"width:100%;\">");
		int i=0;
		double valorTotal = 0;
		for(Cupom cupom : lancamentos) {
			html.append("<tr class=\"tbResultadoConsultaLinha").append(i++ % 2).append("\">");
			html.append("	<td align=\"center\" style=\"width:20px\" class=\"tbResultadoConsultaInfo\">");
			html.append("		<input type=\"radio\" name=\"idSelecionado\" id=\"idSelecionado\" value=\"").append(cupom.getCodigo()).append("\" onclick=\"alterarIniciar('").append(cupom.getCodigo()).append("')\"/>");
			html.append("	</td>");
			html.append("	<td align=\"center\" style=\"width:200px\" class=\"tbResultadoConsultaInfo\">").append(cupom.getDoador().getCnpj()).append("</td>"); 
			html.append("	<td align=\"center\" style=\"width:120px\" class=\"tbResultadoConsultaInfo\">").append(getDateFormat().format(cupom.getData())).append("</td>");
			html.append("	<td align=\"center\" class=\"tbResultadoConsultaInfo\">").append(cupom.getCoo()).append("</td>");
			html.append("	<td align=\"right\" style=\"width:100px\" class=\"tbResultadoConsultaInfo\">").append(getDecimalFormat().format(cupom.getValor())).append("</td>");
			html.append("</tr>");
			valorTotal += cupom.getValor();
		}
		html.append("<tr>");
		html.append("	<td align=\"left\" style=\"width:200px\" class=\"tbResultadoConsultaInfo\" colspan=\"3\">Total: <b>").append(i).append("</b> notas </td>"); 
		html.append("	<td align=\"center\" class=\"tbResultadoConsultaInfo\"></td>");
		//html.append("	<td align=\"right\" style=\"width:100px\" class=\"tbResultadoConsultaInfo\"><b>").append(getDecimalFormat().format(valorTotal)).append("</b></td>");
		html.append("	<td align=\"right\" style=\"width:100px\" class=\"tbResultadoConsultaInfo\"></td>");
		html.append("</tr>");
		html.append("</table>");
		
		response.setContentType("text/html");
		response.getWriter().write(html.toString());
		
		return null;
	}
	
	public ActionForward obterArquivoMacro(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CupomForm cupomForm = (CupomForm) form;
		
		Integer codigoEntidade = cupomForm.getEntidade();
		Entidade entidade = getEntidadeDAO().consultar(new Entidade(codigoEntidade, getUsuario(request))).get(0);

		List<Cupom> lista = getCupomDAO().consultaCupomParaEnvio(getUsuario(request), codigoEntidade);
				
		DecimalFormat d = new DecimalFormat("0.00");
		Date dataAtual = new Date();
		HashMap<String, String> arquivos = new HashMap<String, String>();
		
		SimpleDateFormat sdfCupom = new SimpleDateFormat("MM/yyyy");
		StringBuilder arquivo = new StringBuilder();
		String date = "";
		for(Cupom cupom : lista) {
			if(date.equals("")) {
				date = sdfCupom.format(cupom.getData());
				arquivo = new StringBuilder();
			} else if(!date.equals(sdfCupom.format(cupom.getData()))) {
				arquivos.put(date, arquivo.toString());
				date = sdfCupom.format(cupom.getData());
				arquivo = new StringBuilder();
			}
			arquivo.append(cupom.getCodigo()).append(",");
			arquivo.append(cupom.getUsuarioCadastro().getLogin()).append(",");
			arquivo.append(cupom.getDoador().getCnpj()).append(",");
			arquivo.append(getDateFormat().format(cupom.getData())).append(",");
			arquivo.append(cupom.getCoo()).append(",");
			arquivo.append("\"").append(d.format(cupom.getValor()).replace('.',',')).append("\"");
			arquivo.append("\n");
			getCupomDAO().atualizaEnvioCupom(cupom.getCodigo(), dataAtual);
		}
		arquivos.put(date, arquivo.toString());
		
		response.setContentType("application/zip");
		response.setHeader("Content-Disposition", "attachment;filename=NFEnviar-" + entidade.getRazaoSocial() + "-" + new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(new Date()) + ".zip");
		
		ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
		zip.setLevel(Deflater.DEFAULT_COMPRESSION);		
		
		Iterator<String> chaves = arquivos.keySet().iterator();
		while(chaves.hasNext()) {
			String key = chaves.next();
			String value = arquivos.get(key);
			Date a = new SimpleDateFormat("MM/yyyy").parse(key);
			ZipArchiveEntry entry = new ZipArchiveEntry(new SimpleDateFormat("MM-yyyy").format(a) + ".csv");
			zip.putNextEntry(entry);
			zip.write(value.getBytes());
		}
	
		zip.close();
		
		return null;		
	}
}
